//
//  ViewController.m
//  CoreData
//
//  Created by dllo on 15/11/20.
//  Copyright (c) 2015年 蓝鸥3g学院. All rights reserved.
//

#import "ViewController.h"
#import "LDCoreDataManager.h"
#import "LDTableViewCell.h"
#import "LDViewController.h"
#import "Student.h"
#import "LDAddViewController.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *arr;
@property(nonatomic, strong) LDCoreDataManager *manager;
@property(nonatomic, strong) UISearchBar *search;
@property(nonatomic, strong) UITableView *searchView;
@property(nonatomic, strong) NSMutableArray *array;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375, 667) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = 80;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(click:)];
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.manager = [LDCoreDataManager defaults];
//    [self createDate];
    self.tableView.hidden = NO;
    
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 200, 10)];
    self.navigationItem.titleView = self.search;
    self.search.placeholder = @"请输入搜索名字";
    self.search.delegate = self;
    

}



- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
//    
//    NSPredicate *predicate = [NSPredicate predicateWithValue:YES];
//
//    request.predicate = predicate;
//    
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
//    
//    NSError *error;
//    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
//    
//    self.arr = [NSMutableArray arrayWithArray:array];
//    [self.tableView reloadData];
    
    
    if (searchText != nil) {
        // 初始化
        self.array = [NSMutableArray array];
      
        
        
        for (Student *per in self.arr) {
            // 搜索成功
            if ([per.name containsString:searchText] || [per.phone containsString:searchText] || [per.sex containsString:searchText] || [per.number containsString:searchText] ||[per.qq containsString:searchText] || [per.address containsString:searchText]) {
                [self.array addObject:per];
                
            }
            
        }
        
        if (searchText.length != 0) {
            
            if (self.array.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有找到联系人" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];

            } else {
                
                [self.tableView reloadData];
            }
        } else {
            
            self.array = nil;
            [self.tableView reloadData];
        }
    }
    
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    self.search.showsCancelButton = YES;
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.search resignFirstResponder];
    [self.search setShowsCancelButton:NO animated:YES];
    self.array = [NSMutableArray array];
    [self createDate];
    [self.tableView reloadData];
    searchBar.text = nil;
    
}

#pragma mark 删除数据
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    Student *stu = self.arr[indexPath.row];
    UITableViewRowAction *secondAction = [UITableViewRowAction rowActionWithStyle:0 title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        Student *stu = self.arr[indexPath.row];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], stu.name];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        [self.arr removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:2];
        
        for (Student *student in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:student];
        }

        [self.manager saveContext];

    }];

    return @[secondAction];
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}


#pragma mark 获取数据
- (void)createDate {
    if (self.arr.count == 0) {
        self.arr = [NSMutableArray array];
    }
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
    NSPredicate *pre = [NSPredicate predicateWithValue:YES];
    request.predicate = pre;
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error;
    NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    
    self.arr = [NSMutableArray arrayWithArray:array];
    [self.tableView reloadData];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self createDate];
    self.array = [NSMutableArray array];
    [self.tableView reloadData];
    self.search.text = nil;
    self.search.showsCancelButton = NO;
}

- (void)click:(UIBarButtonItem *)button {
    LDAddViewController *add = [[LDAddViewController alloc] init];
    [self.navigationController pushViewController:add animated:YES];
}


#pragma mark tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.array.count == 0) {
        return self.arr.count;
    } else {
       return self.array.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    LDTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[LDTableViewCell alloc] initWithStyle:0 reuseIdentifier:reuse];
    }
    if (self.array.count == 0) {
        Student *stu = self.arr[indexPath.row];
        cell.upLabel.text = [NSString stringWithFormat:@"姓名: %@", stu.name];
        cell.downLabel.text = [NSString stringWithFormat:@"性别: %@", stu.sex];
        cell.midLabel.text = [NSString stringWithFormat:@"学号: %@", stu.number];
    } else {
        Student *stu = self.array[indexPath.row];
        cell.upLabel.text = [NSString stringWithFormat:@"姓名: %@", stu.name];
        cell.downLabel.text = [NSString stringWithFormat:@"性别: %@", stu.sex];
        cell.midLabel.text = [NSString stringWithFormat:@"学号: %@", stu.number];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LDViewController *view = [[LDViewController alloc] init];
    if (self.array.count == 0) {
        Student *stu = self.arr[indexPath.row];
        view.stu = stu;

    } else {
        Student *stu = self.array[indexPath.row];
        view.stu = stu;
    }
    
    

    [self.search resignFirstResponder];
    [self.navigationController pushViewController:view animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
